package cn.ccenjie.wsy.config.jwt;

import cn.ccenjie.wsy.utils.HttpUtils;
import cn.ccenjie.wsy.vo.Resp;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

public class JwtSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        // 所有的验证都通过了，生成jwt
        String token = Jwts.builder()
                .setSubject(authentication.getName())
                .claim(Jwtconst.USER_KEY, authentication)
                .claim(Jwtconst.AUTHORITYS_KEY, authentication.getAuthorities())
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 1000))
                .signWith(SignatureAlgorithm.HS512, Jwtconst.SIG_KEY)
                .compact();

        HttpUtils.wrire(response, Resp.ok().data("token", token));

    }


}
